package com.lagou.edu.utils;

import com.lagou.edu.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;

@Service
public class ConnectionUtils {

    //存储当前线程的连接
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 从当前线程中获取连接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        //判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取⼀个连接绑定到当前线程
        Connection connection = threadLocal.get();
        if (connection == null) {
            //从线程池中获取连接并绑定到当前线程
            connection = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
}
